const fs = require('fs')

class Localize {
    constructor() {

    }

    apply(resolver) {
        resolver.getHook('before-existing-file')
            .tapAsync('LocalizationResolver', function(request, resolveContext, callback) {
                var locale = process.env.LOCALE
                // 不存在特例字符，直接callback
                if (!locale || !/\w*-\w*/.exec(locale)) {
                    return callback()
                }
                var parts = /(.*\.)([^./\\]*)/.exec(request.path);
                var filePathAndName = parts[1]
                var fileExt = parts[2]
                var [lang, specialCaseWord] = locale.split('-') // 区域, 特例

                var fullLocalizedPath = `${filePathAndName}${lang}.${specialCaseWord}.${fileExt}`
                if (fs.existsSync(fullLocalizedPath)) {
                    request.path = fullLocalizedPath
                }

                callback()
            })
    }
}

module.exports = Localize